<?php

declare (strict_types = 1);

namespace app\admin\middleware;

use app\common\Token;
use app\model\Store;

class Auth
{
    /**
     * 处理请求
     * 利用jwt验证token中间件
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {

        $white_list = [
            '/admin/auth/login',
            '/admin/auth/codeImg',
        ];

        $request_uri = $_SERVER['REQUEST_URI'];
        $pathinfo    = explode('?', $request_uri)[0];
        // $pathinfo    = strtolower($pathinfo);

        // var_dump(in_array($pathinfo, $white_list));

        //排除白名单
        if (in_array($pathinfo, $white_list)) {
            // echo '白名单';
            return $next($request);

        } else {
            //验证登录

            if (! $request->header('token')) {
                return json(['code' => 302, 'msg' => 'token不存在']);
            }

            $token = $request->header('token');

            if (Token::verifyToken($token)) {
                $data = Token::getDataByToken($token);

                if ($data['code'] == 200) {
                    $uid          = (array)$data['data']['data'];
                    $uid          = $uid['uid'];
                    $request->uid = $uid;

                    //验证权限
                    $admin = \app\model\Admin::with(['role.permissions'])
                        ->where('id', $uid)
                        ->find();

                    if (empty($admin)) {
                        return json(['code' => 400, 'msg' => '该管理员不存在']);
                    }

                    // echo $admin['store_id'];

                    // 查询店铺信息
                    $store = Store::where('id', $admin['store_id'])->find();


                    if (empty($store)) {
                        return json(['code' => 400, 'msg' => '管理员未绑定店铺']);
                    }
                    // 将店铺信息存储到请求中
                    $request->storeId = $store->id;
                    // var_dump($request->storeId);

                    if ($uid == 5) {
                        return $next($request);
                    }


                    $permissions      = $admin->role->permissions;

                    // 检查当前请求路径是否有权限访问
                    $hasPermission = false;
                    foreach ($permissions as $permission) {
                        if ($permission['path'] === $pathinfo) {
                            $hasPermission = true;
                            break;
                        }
                    }

                    if (! $hasPermission) {
                        return json(['code' => 403, 'msg' => '无权限访问']);
                    }

                    // 验证通过，继续执行下一个中间件或路由处理函数
                    return $next($request);
                } else {
                    return json(['code' => 302, 'msg' => $data['msg']]);
                }

                return $next($request);
            } else {
                return json(['code' => 302, 'msg' => 'token有误']);
            }
        }
    }
}
